<?php
	
	class FileUploadHandler {
		
		private $filepath = "Files/";
		private $m_fileList = array();
		
		const UPLOAD_SUCCES = "Succsess! The file is now uploaded!";
		const FILE_EXISTS = "File already exists!";
		const FILE_TO_LARGE = "The file is to large!";
		const FILE_NO_IMAGE = "The file is not an image!";
		
		//Hämtar en array med de uppladdade filerna
		public function GetFiles(){
				
			if (is_dir($this->filepath)) {
			    	
			    if ($dh = opendir($this->filepath)) {
			        while (($file = readdir($dh)) !== false) {
	            		//Skriver bara ut jpg-, png- och gif- filer
		            	if(strchr($file, '.') == ".jpg" ||
		            		strchr($file, '.') == ".gif" ||
		            		strchr($file, '.') == ".png"){
			            	$this->m_fileList [] = $file;
						}
			        }
			        closedir($dh);
		    	}
			}
			return $this->m_fileList;
		}
		
		//Tar emot och sparar en fil.
		public function SaveFile($file){
				
			if ($file["error"] > 0) {
		    	return "Return Code: " . $file["error"] . "<br />";
		    } else {
		    	
		    	//Är filen av image-format?
	    		if($this->IsImage($file)){
    				
					//Har bilden godkänd storlek?
	    			if($this->IsRightSize($file)){
	    				
			    		//Finns bilden redan i mappen?
			    		if (file_exists($this->filepath . $fileName)){
				      		return self::FILE_EXISTS;
				      	} else {
			      			
			      			//Spara filen i Files mappen och returnera 
					      	move_uploaded_file($file["tmp_name"],
					      	$this->filepath . $fileName);
							return self::UPLOAD_SUCCES;
				      	}
					} else {
						return self::FILE_TO_LARGE;
					}
				} else{
					return self::FILE_NO_IMAGE;
				}
			}
		}
		//Kollar så att filen är av godkännt bild-format
		public function IsImage($file){
				
			if($file["type"] == "image/jpeg" || 
				$file["type"] == "image/png" || 
				$file["type"] == "image/gif") {
	    	   	return TRUE;
		   	}	else{ return FALSE; }
			   
		}
		//Kollar så att filen inte är för stor
		public function IsRightSize($file){
				
			if($file["size"] <= 4000000){
				return TRUE;
			} else { return FALSE; }
		}
	}
?>